package nbcp

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.core.convert.ConversionService
import org.springframework.core.convert.TypeDescriptor
import org.springframework.core.convert.converter.Converter
import org.springframework.core.convert.converter.ConverterFactory
import org.springframework.core.convert.converter.GenericConverter
import org.springframework.core.convert.support.GenericConversionService

import javax.annotation.PostConstruct

class MyConversionService : ConversionService {

    @Autowired
    private val conversionService: GenericConversionService? = null
    var converters: MutableSet<Any> = mutableSetOf()

    @PostConstruct
    fun afterPropertiesSet() {

        for (converter in converters) {
            if (converter is Converter<*, *>) {
                conversionService!!.addConverter(converter)
            } else if (converter is ConverterFactory<*, *>) {
                conversionService!!.addConverterFactory(converter)
            } else if (converter is GenericConverter) {
                conversionService!!.addConverter(converter)
            }
        }

    }

    override fun canConvert(sourceType: Class<*>?, targetType: Class<*>): Boolean {
        return conversionService!!.canConvert(sourceType, targetType)
    }

    override fun canConvert(sourceType: TypeDescriptor?,
                            targetType: TypeDescriptor): Boolean {
        return conversionService!!.canConvert(sourceType, targetType)
    }

    override fun <T> convert(source: Any?, targetType: Class<T>): T? {
        return conversionService!!.convert(source, targetType)
    }

    override fun convert(source: Any?, sourceType: TypeDescriptor?,
                         targetType: TypeDescriptor): Any? {
        return conversionService!!.convert(source, sourceType, targetType)
    }
}
